<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>leaflet实现测量面积</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
    <style>
        #mapButton {
            position: absolute;
            z-index: 10000;
        }

        html,
        body,
        #map {
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="mapButton">
        <br><br><br><br>
        <button type="button" id="areaMeasure">测面积</button>
        <button type="button" id="clearMeasure">清除</button>
    </div>
    <div id="map">
    </div>
    <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    <script type="text/javascript">
        const markerStyle = {
            color: '#676767',
            weight: 1,
            fillOpacity: 1,
            fillColor: '#fff',
            radius: 3
        }
        const tooltipStyle = {
            direction: 'top', // 方向
            offset: L.point(0, -3), // 偏移
            interactive: true,
            permanent: true // 永久提示
        }
        let layers = {}
        let layerId = ''
        

        var map = L.map('map').setView([36.09, 120.35], 13);
        L.tileLayer('http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}', {
            attribution: ''
        }).addTo(map);

        var DRAWING = false; //是否正在绘制
        var BarDRAWLAYERS = [];
        var MEASUREAREATOOLTIP; //量面提示
        var DRAWPOLYGON; //绘制的面
        var DRAWMOVEPOLYGON; //绘制过程中的面
        var DRAWPOLYGONPOINTS = []; //绘制的面的节点集

        var MEASURERESULT = 0; //测量结果
        // let layerGroup = L.layerGroup().addTo(map)
        //测量面积按钮点击事件
        $('#areaMeasure').click(function () {
            //开始绘制多边形
            startDrawPolygon();
        });

        /*多边形*/
        function startDrawPolygon(func) {
            layerId = +new Date()
            let layerGroup = L.layerGroup().addTo(map)
            layers[layerId] = layerGroup

            MEASURERESULT = 0;
            map.getContainer().style.cursor = 'crosshair';
            //地图添加鼠标按下事件
            map.on('click', function (e) {
                DRAWING = true;
                DRAWPOLYGONPOINTS.push(e.latlng);
                DRAWPOLYGON.addLatLng(e.latlng);
            });
            //地图添加鼠标移动事件
            map.on('mousemove', function (e) {
                if (DRAWING) {
                    //清除上次数据
                    if (DRAWMOVEPOLYGON != undefined && DRAWMOVEPOLYGON != null) {
                        map.removeLayer(DRAWMOVEPOLYGON);
                    }
                    var prevPoint = DRAWPOLYGONPOINTS[DRAWPOLYGONPOINTS.length - 1];
                    var firstPoint = DRAWPOLYGONPOINTS[0];
                    DRAWMOVEPOLYGON = new L.Polygon([firstPoint, prevPoint, e.latlng], shapeOptions).addTo(layerGroup)
                    // map.addLayer(DRAWMOVEPOLYGON);
                    // console.log(DRAWMOVEPOLYGON,'DRAWMOVEPOLYGON')
                }
            });

            //地图添加鼠标双击事件
            map.on('dblclick', function (e) {
                map.getContainer().style.cursor = '';
                var tempPoints = [];
                for (var i = 0; i < DRAWPOLYGONPOINTS.length; i++) {
                    tempPoints.push(DRAWPOLYGONPOINTS[i]);
                }
                tempPoints.push(e.latlng);
                //计算面积
                var distance = CalArea(tempPoints);
                //声明标记
                // marker = new L.Marker(e.latlng, {
                //     draggable: false
                // });
                marker = L.circleMarker(e.latlng, markerStyle)
                .bindTooltip('', tooltipStyle)
                .openTooltip()
                .addTo(layerGroup)
                //地图上添加标记
                // map.addLayer(marker);
                //标记弹窗显示面积
                let content = "总面积：" + (distance / 1000000).toFixed(3) + '平方公里'
                marker.setTooltipContent(setTipText(content, layerId)).openPopup()
                // marker.bindPopup("总面积：" + (distance / 1000000).toFixed(3) + '平方公里').openPopup()
                if (DRAWING) {
                    if (DRAWMOVEPOLYGON != undefined && DRAWMOVEPOLYGON != null) {
                        map.removeLayer(DRAWMOVEPOLYGON);
                        DRAWMOVEPOLYGON = null;
                    }
                    BarDRAWLAYERS.push(DRAWPOLYGON);
                    if (func) {
                        func(DRAWPOLYGONPOINTS);
                    }
                    DRAWPOLYGONPOINTS = [];
                    DRAWING = false;
                    //地图移除事件
                    map.off('click');
                    map.off('mousemove');
                    map.off('dblclick');

                    startDrawPolygon()
                    
                }
                
            });

            var shapeOptions = {
                color: '#F54124',
                weight: 3,
                opacity: 0.8,
                fill: true,
                fillColor: null,
                fillOpacity: 0.2,
                clickable: true
            },

                DRAWPOLYGON = new L.Polygon([], shapeOptions);
                layerGroup.addLayer(DRAWPOLYGON)
            // map.addLayer(DRAWPOLYGON);

            //计算面积
            function CalArea(latLngs) {
                var pointsCount = latLngs.length,
                    area = 0.0,
                    d2r = Math.PI / 180,
                    p1, p2;
                if (pointsCount > 2) {
                    for (var i = 0; i < pointsCount; i++) {
                        p1 = latLngs[i];
                        p2 = latLngs[(i + 1) % pointsCount];
                        area += ((p2.lng - p1.lng) * d2r) *
                            (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r));
                    }
                    area = area * 6378137.0 * 6378137.0 / 2.0;
                }
                return Math.abs(area);
            }
        }

        //清除按钮点击事件
        $('#clearMeasure').click(function () {
            qingchu()
       
        })

        //执行清除方法
        function qingchu(func) {
            for (var i = 0; i < BarDRAWLAYERS.length; i++) {
                //移除图层
                map.removeLayer(BarDRAWLAYERS[i]);
            }
            
            //清空数组
            BarDRAWLAYERS = [];
            if (marker) {
                map.removeLayer(marker)
            }
            for(let l in layers) {
                let layer = layers[l]
                layer.clearLayers()
            }
            layers = {}
            DRAWPOLYGONPOINTS = [];
            DRAWING = false;
            //地图移除事件
            map.off('click');
            map.off('mousemove');
            map.off('dblclick');
            map.getContainer().style.cursor = '';
        }
        // 结束绘制，移除图层
        function remove(layerId) {
        layers[layerId] && layers[layerId].remove()
        delete layers[layerId]
        }

        // 自定义 展示框
        function setTipText(content, layerId) {
            const el = document.createElement("div");
            el.className = "measure-marker";

            const text = document.createElement("span");
            text.className = "measure-text";
            text.innerHTML = content;
            text.style.pointerEvents = 'none'

            const close = document.createElement("span");
            close.className = "measure-close";
            close.innerHTML = '【删除】';

            close.addEventListener("click", (e) => {
                e.stopPropagation() 
                
                let ls = layers[layerId]
                ls.clearLayers()
                delete layers[layerId]
                setTimeout(() => {
                    console.log(layers,'layers')
                },2999)
                // remove(layerId)
                // 
                // qingchu()
            });

            el.appendChild(text)
            el.appendChild(close)

            return el
        }
    </script>
</body>

</html>